package com.truyen.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.captcha.Captcha;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.producer.NumbersAnswerProducer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.truyen.model.AuthInfo;
import com.truyen.persistence.entity.Account;
import com.truyen.persistence.entity.TruyenTranh;
import com.truyen.persistence.entity.UserLiked;
import com.truyen.persistence.entity.BookmarkChapter;
import com.truyen.service.BookmarkChapterService;
import com.truyen.service.MailService;
import com.truyen.service.TruyenTranhService;
import com.truyen.service.UserService;
import com.truyen.service.UserLikedService;

@Controller
public class HomeController {
	
	@Autowired
	@Qualifier("userDetailService")
	private UserService userService;
	
	@Autowired
	private UserLikedService userLikedService;
	
	@Autowired
	private TruyenTranhService truyenTranhService;
	
	@Autowired
	private BookmarkChapterService bookmarkChapterService;
	
	@Autowired
	private MailService mailService;
	
	@RequestMapping("/dang-nhap.htm")
	public String dangNhap() {
		return "/login/login";
	}
	
	//captcha 5 ky tu
	@RequestMapping("/captcha5.htm")
	@ResponseBody
	public void catpcha5(Model model,HttpServletRequest request,HttpServletResponse response){
		Captcha captcha = new Captcha.Builder(200, 50)
		.addText()
//		.addBackground(new GradiatedBackgroundProducer())
//        .gimp()
        .addNoise()
//        .addBorder()
        .build();
		CaptchaServletUtil.writeImage(response, captcha.getImage());
		request.getSession().setAttribute("Captcha5", captcha);
	}
	
	//captcha 3 so dung de binh luan
	@RequestMapping("/captcha3.htm")
	@ResponseBody
	public void catpcha3(Model model,HttpServletRequest request,HttpServletResponse response){
		Captcha captcha = new Captcha.Builder(70, 50)
		.addText(new NumbersAnswerProducer(3))
        .addNoise()
        .build();
		CaptchaServletUtil.writeImage(response, captcha.getImage());
		request.getSession().setAttribute("Captcha3", captcha);
	}
	
	//captcha 3 so dung de gop y
	@RequestMapping("/captcha3Feedback.htm")
	@ResponseBody
	public void captcha3Feedback(Model model,HttpServletRequest request,HttpServletResponse response){
		Captcha captcha = new Captcha.Builder(70, 50)
		.addText(new NumbersAnswerProducer(3))
        .addNoise()
        .build();
		CaptchaServletUtil.writeImage(response, captcha.getImage());
		request.getSession().setAttribute("Captcha3Feedback", captcha);
	}
	
	@RequestMapping("/account/redirect.htm")
	@PreAuthorize("hasRole('ROLE_USER')")
	public String redirectAllowRole(){
		Account account = userService.getCurrentLoggedInUser();
		switch (account.getLevel()) {
	        case 3:
	        	return "redirect:/admin/main.htm";
	        default:
	        	return "redirect:/account/login.htm";
	    }
	}
	
	@RequestMapping(value = "/account/authenticate.htm", method = {
			RequestMethod.POST, RequestMethod.GET })
	public @ResponseBody boolean authenticate(@ModelAttribute AuthInfo authInf) {
		return userService.authenticate(authInf.getUserName(), 
				authInf.getPwd());
	}
	
	@RequestMapping("/trang-loi.htm")
	public String error404(Model model) {
		return "/errorPage/loi404";
	}
	
	//check account
	@RequestMapping("/check-account.htm")
	@ResponseBody
	public boolean checkAccount(@RequestParam String cl,@RequestParam String val){
		boolean flag = false;
		if(cl != null && !cl.equals("") && val != null && !val.equals("")){
			Account acc = userService.findItemByProperty(cl, val);
			if(acc != null){
				flag = true;
			}
		}
		return flag;
	}
	
	//yeu thich truyen
	@RequestMapping("/yeu-thich-truyen.htm")
	@ResponseBody
	public boolean userLiked(@RequestParam String nameTruyen,@RequestParam Long id,@RequestParam String urlTruyen){
		boolean flag = false;
		if(id!=null && id > 0 && nameTruyen != null && !nameTruyen.equals("") && urlTruyen != null && !urlTruyen.equals("")){
			Account account = userService.findById(id);
			if(account != null){
				UserLiked userLiked = userLikedService.findByProperty("urlTruyen", urlTruyen);
				if(userLiked == null){
					userLiked = new UserLiked(account,urlTruyen,new Date(),nameTruyen);
					userLikedService.save(userLiked);
				}else{
					userLikedService.delete(userLiked.getId());
				}
				flag=true;
			}
		}
		return flag;
	}
	
	//book mark truyen
	@RequestMapping("/ghi-nho-chapter-dang-doc.htm")
	@ResponseBody
	public boolean bookMark(@RequestParam String nameChapter,@RequestParam Long id,@RequestParam String urlChapter,long idChapter, long idTruyen){
		boolean flag = false;
		if(nameChapter != null && id!=null && id > 0 && idChapter > 0 && idTruyen > 0){
			Account account = userService.findById(id);
			if(account !=null){
				BookmarkChapter bookmarkChapter = bookmarkChapterService.findByProperty("urlChapter", urlChapter);
				if(bookmarkChapter == null){
					bookmarkChapter = new BookmarkChapter(account,urlChapter,new Date(),nameChapter,idChapter,idTruyen);
					bookmarkChapterService.save(bookmarkChapter);
				}else{
					bookmarkChapterService.delete(bookmarkChapter.getId());
				}
				flag = true;
			}
		}
		return flag;
	}
	
	//feedback
	@RequestMapping("/gop-y.htm")
	@ResponseBody
	public boolean feedback(Model model, HttpServletRequest request,
			@RequestParam String email, @RequestParam String contentFeedBack,
			@RequestParam String answer) throws Exception {
		boolean flag = false;
		if (email != null && !email.equals("") && contentFeedBack != null
				&& !contentFeedBack.equals("") && answer != null && !answer.equals("")) {
			Captcha captcha = (Captcha) request.getSession().getAttribute("Captcha3Feedback");
			if (captcha.isCorrect(answer)) {
				mailService.sendNotify("GÓP Ý TRUYENZ.COM !", "Từ email : "+email+"\n\n Nội dung : \n\n"+contentFeedBack, "admin@truyenz.com");
				Account account = userService.findItemByProperty("email", email);
				if (account != null) {
					userService.updateColumLong(account.getId(), "toCoin", 10);
				}
				mailService.sendNotify("Lời cảm ơn từ TRUYENZ.COM !", "Chân thành cảm ơn bạn đã góp ý về trang TRUYENZ.COM. Chúng tôi sẽ xem góp ý của bạn và sẽ nâng cấp TRUYENZ.COM để phục vụ bạn tốt hơn", email);
				flag = true;
			}
		}
		return flag;
	}
	
}
